package com.randev.snapservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;

import com.randev.snapconfig.Config;

public class LocationAddressService extends AsyncTask<Object, Void, String> {

	private Messenger addressMessenger;
	private final String TAG = "LocationAddressService";
	private Context context;
	
	@Override
	protected String doInBackground(Object... params) {

		addressMessenger = (Messenger) params[0];
		Bundle bundle = (Bundle) params[1];
		context = (Context) params[2];
		
		Message addressMessage = Message.obtain();
		addressMessage.arg1 = 1;
		try {
			addressMessenger.send(addressMessage);
		} catch (android.os.RemoteException e1) {
			Log.w(TAG, "Exception sending progress message", e1);
		}
		
		String longitude = bundle.getString(Config.LONGITUDE);
		String latitude =  bundle.getString(Config.LATITUDE);
		
		JSONObject jsonResponse = new JSONObject();
		String address = "";
		
		if (isNetworkAvailable()) {
			jsonResponse = getLocationFromLatAndLong(latitude, longitude);
			
			if (jsonResponse.length() != 0) {
				address = getAddressFromJson(jsonResponse);
			} else {
				Log.w(TAG, "doInBackgroud: JSON empty");
			}
		}
		
		
		
		
		return address;
	    
	}
	
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		
		Message addressMessage = Message.obtain();
		Bundle bundle = new Bundle();
		addressMessage.arg1 = 2;
		bundle.putString(Config.ADDRESS, result);
		addressMessage.setData(bundle);
		try {
			addressMessenger.send(addressMessage);
		} catch (android.os.RemoteException e1) {
			Log.w(TAG, "Exception sending progress message", e1);
		}
	}

	private JSONObject getLocationFromLatAndLong(String latitude, String longitude){
		String getAddressString = Config.ADDRESS_GET;
		StringBuilder stringBuilder = new StringBuilder();
		String url = getAddressString+ latitude+ ","+ longitude+ "&sensor=true";
		HttpGet addressGet = new HttpGet(url); 	
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = null;
		JSONObject responseJson = null;
		
		try {
			response = httpClient.execute(addressGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
		        InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		        String line = "";
		        while ((line = reader.readLine()) != null) {
		        	stringBuilder.append(line);
		        }
				
				
				responseJson = new JSONObject(stringBuilder.toString());
			} else {
		    	Log.w(TAG, "invalid response from server: " + statusCode);
		    }
			
		} catch (ClientProtocolException e) {
			Log.w(TAG, "getLocationFromLatAndLong" + e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			Log.w(TAG, "getLocationFromLatAndLong" + e.toString());
		} catch (JSONException e) {
			Log.w(TAG, "getLocationFromLatAndLong" + e.toString());
		}
		
		return responseJson;
		
	}
	
	
	private String getAddressFromJson(JSONObject responseJson){
		String address = "";
		
		try {
			if (responseJson.getString("status").equalsIgnoreCase("ok")) {
			    JSONArray addressArray = responseJson.getJSONArray("results");
			    
			    if(addressArray.length() != 0) {
			        JSONObject geoAddress = addressArray.getJSONObject(0);
			        address = geoAddress.getString("formatted_address");
			    }
			    Log.e("address", address);
			}
		} catch (JSONException e) {
			Log.w(TAG, "getAddressFromJson" + e.toString());
		}
		
		return address;
	}
	
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
	    return networkInfo != null && networkInfo.isConnectedOrConnecting();
	}
	
	
}
